package com.example.administrator.printoutindemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.printoutindemo.services.dyjApplication;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.zhinenghuacangku.mvp.ui.activity.ScanQRCodeActivity;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;


public class StoreListRecoveryActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;
    private static final int LOADRECOVERYLIST = 4;
    private static final int UPSUCCESS = 5;
    private static final int UPERROR = 6;
    AutoCompleteTextView store_recovery_project = null;
    ImageView mBtnRight;
    ProgressDialog progressDiaog;
    private ProjectInfo projectInfo = null;
    private List<ProjectInfo> li_projectInfo = null;
    private List<RecoveryInfo> li_recoveryInfo = null;
    private StoreListRecoveryAdapter adapter = null;
    private RecoveryInfo recoveryInfo = null;
    private ListView store_recovery_listView = null;
    private MyImageButton store_btn_QRCode = null;
    private MyAutoAarryAdapter projectAda = null;
    private Button store_recovery_submit = null;
    private String scanResult = "";
    private String[] permissions = {android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private String SYSException = "";
    @SuppressLint("HandlerLeak")
    private final Handler hanlder = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case LOGINSUCCESS:
                    bindProjectInfo();

                    progressDiaog.dismiss();
                    break;
                case LOADRECOVERYLIST:
                    bindListView();
                    progressDiaog.dismiss();
                    break;
                case UPSUCCESS:
                    Toast.makeText(StoreListRecoveryActivity.this, "上传数据成功!",
                            Toast.LENGTH_LONG).show();


                    progressDiaog.dismiss();
                    break;
                case UPERROR:
                    Toast.makeText(StoreListRecoveryActivity.this, "上传数据失败!",
                            Toast.LENGTH_LONG).show();
                    progressDiaog.dismiss();
                    break;

                case NETWORKERROR:

                    Toast.makeText(StoreListRecoveryActivity.this, "网络或系统异常!",
                            Toast.LENGTH_LONG).show();
                    progressDiaog.dismiss();
                    break;
                case SYSERROR:

                    Toast.makeText(StoreListRecoveryActivity.this,
                            "系统异常!" + SYSException, Toast.LENGTH_LONG).show();
                    progressDiaog.dismiss();
                    break;

                default:
                    progressDiaog.dismiss();
                    break;
            }

        }
    };
    private SharedPreferences sPreferencces;

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_listrecovery);
        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);
        ToolbarUtils.initToolbarTitleBack(this, "报废回收扫码");

        mBtnRight = findViewById(R.id.btnRight);
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        mBtnRight.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getPermission()) {
                    toScanQRCodeActivity();
                }
            }
        });

        store_recovery_project = (AutoCompleteTextView) findViewById(R.id.store_recovery_project);// 项目
        store_recovery_listView = (ListView) findViewById(R.id.store_recovery_listView);

        adapter = new StoreListRecoveryAdapter(this);

        store_btn_QRCode = (MyImageButton) findViewById(R.id.store_btn_QRCode);
        store_recovery_submit = (Button) findViewById(R.id.store_recovery_submit);

        recoveryInfo = new RecoveryInfo();
        projectInfo = new ProjectInfo();

        store_btn_QRCode.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 扫码
                Intent openCameraIntent = new Intent(
                        StoreListRecoveryActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });
        store_recovery_submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //上传

                if (store_recovery_project.getText().toString().equals("")) {
                    Toast.makeText(StoreListRecoveryActivity.this, "请填写项目名称!",
                            Toast.LENGTH_LONG).show();
                } else if (li_recoveryInfo == null) {
                    Toast.makeText(StoreListRecoveryActivity.this, "请扫码确认报废回收物料!",
                            Toast.LENGTH_LONG).show();
                } else {
                    new AlertDialog.Builder(StoreListRecoveryActivity.this)
                            .setTitle("提交确认")
                            .setMessage("您确认要提交吗？")
                            .setPositiveButton("确认",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            progressDiaog = new ProgressDialog(StoreListRecoveryActivity.this);
                                            progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
                                            progressDiaog.setTitle("提示");
                                            // progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
                                            progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
                                            progressDiaog.setIndeterminate(false);// 设置进度条不明确
                                            progressDiaog.setCancelable(true);

                                            progressDiaog.show();

                                            new Thread(new Runnable() {

                                                @Override
                                                public void run() {

                                                    String re = "0";

                                                    String[] projectId = store_recovery_project.getText().toString().split("\\|");

                                                    for (RecoveryInfo rec : li_recoveryInfo) {
                                                        rec.set_projectId(projectId[1]);
                                                        re += UploadRecoveryInfo(rec);
                                                    }


                                                    if (Integer.parseInt(re) > 0) {
                                                        Message m = new Message();
                                                        m.what = StoreListRecoveryActivity.UPSUCCESS;
                                                        hanlder.sendMessage(m);

                                                    } else {
                                                        Message m = new Message();
                                                        m.what = StoreListRecoveryActivity.UPERROR;
                                                        hanlder.sendMessage(m);
                                                    }

                                                }
                                            }).start();
                                        }
                                    })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .show();


                }


            }
        });

        progressDiaog = new ProgressDialog(StoreListRecoveryActivity.this);
        progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
        progressDiaog.setTitle("提示");
        // progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
        progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
        progressDiaog.setIndeterminate(false);// 设置进度条不明确
        progressDiaog.setCancelable(true);

        progressDiaog.show();
        new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    int user_id = ((dyjApplication) getApplication())
                            .get_user_id();
                    li_projectInfo = callWebServiceGetProjectInfo(String
                            .valueOf(user_id));

                    if (li_projectInfo != null) {
                        Message m = new Message();
                        m.what = StoreListRecoveryActivity.LOGINSUCCESS;
                        hanlder.sendMessage(m);
                    }

                } catch (Exception e) {
                    Message m = new Message();
                    m.what = StoreListRecoveryActivity.SYSERROR;
                    hanlder.sendMessage(m);
                }

            }
        }).start();

    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    private void toScanQRCodeActivity() {
        Intent newIntent = new Intent(this, ScanQRCodeActivity.class);
        SharedPreferences.Editor editor = sPreferencces.edit();
        editor.putInt(SCAN_REQUEST_CODE, 101);
        editor.commit();
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    // 上传
    private String UploadRecoveryInfo(RecoveryInfo rec) {

        String result = "0";

        String jsonStr = recoveryInfo.ConvertToJson(rec);
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "InsertRecoveryInfo";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("modelJson", jsonStr);
            // request.addProperty("pass", edtPwd.getText().toString());
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                result = returnStr;

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private List<ProjectInfo> callWebServiceGetProjectInfo(String user_id) {

        List<ProjectInfo> result = null;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetModelListRecoveryProjectInfo";

            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            // request.addProperty("keyword", keyWord);
            request.addProperty("user_id", user_id);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();

                if (!t.equals("")) {
                    result = projectInfo.getListFromJSON(t);
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            // TODO: handle exception
            progressDiaog.dismiss();
            SYSException = e.toString();
        }

        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("scan_result");
            // lbl_QRCode.setText(scanResult);

            progressDiaog = new ProgressDialog(StoreListRecoveryActivity.this);
            progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
            progressDiaog.setTitle("提示");
            // progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
            progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
            progressDiaog.setIndeterminate(false);// 设置进度条不明确
            progressDiaog.setCancelable(true);

            progressDiaog.show();

            new Thread() {
                @Override
                public void run() {

                    li_recoveryInfo = callWebServiceGetRecoveryAndroidInfo(scanResult);

                    if (li_recoveryInfo.size() > 0) {

                        Message m = new Message();
                        m.what = StoreListRecoveryActivity.LOADRECOVERYLIST;
                        hanlder.sendMessage(m);
                    }
                }
            }.start();

        }
    }

    private List<RecoveryInfo> callWebServiceGetRecoveryAndroidInfo(
            String out_storage_detail_Id) {

        List<RecoveryInfo> result = null;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetRecoveryAndroidInfo";

            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            // request.addProperty("keyword", keyWord);
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();

                if (!t.equals("")) {
                    result = recoveryInfo.getListFromJSON(t);
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            // TODO: handle exception
            progressDiaog.dismiss();
            SYSException = e.toString();
        }

        return result;
    }

    // 绑定项目信息
    private void bindProjectInfo() {

        List<String> li_projects = new ArrayList<String>();
        if (li_projectInfo.size() > 0) {
            for (ProjectInfo p : li_projectInfo) {
                li_projects.add(p.get_projectname() + "|" + p.get_proid());
            }
        }

        projectAda = new MyAutoAarryAdapter(StoreListRecoveryActivity.this,
                R.layout.store_adapter_mylist_item, li_projects);
        store_recovery_project.setAdapter(projectAda);
    }

    private void bindListView() {

        adapter.setList(li_recoveryInfo);
        store_recovery_listView.setAdapter(adapter);
    }
}